package de.QuizCommunity.service;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import de.QuizCommunity.domain.Antwort;


public class Antwort_Put {

	public static void postAntwort(Antwort antwort) {
		// Create a new HttpClient and Post Header
		HttpClient httpclient = new DefaultHttpClient();
		HttpPost httppost = new HttpPost(
				"http://10.0.2.2:8080/QuizCommunity/rest/webservice/antwort");

		try {
			// Add your data

			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
			
			 nameValuePairs.add(new BasicNameValuePair("frageid",
			 ""+getMaxIdFrage()));
			 nameValuePairs.add(new
			 BasicNameValuePair("antworttext",antwort.getAntworttext()));
			 nameValuePairs.add(new BasicNameValuePair("richtig",
			 ""+antwort.getRichtig()));
			 nameValuePairs.add(new BasicNameValuePair("longitude",
			 ""+antwort.getLongitude()));
			 nameValuePairs.add(new BasicNameValuePair("latitude",
			 ""+antwort.getLatitude()));
			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			httppost.setHeader("Content-type",
					"application/x-www-form-urlencoded; charset=UTF8");

			// Execute HTTP Post Request
			HttpResponse response = httpclient.execute(httppost);

		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
		} catch (IOException e) {
			// TODO Auto-generated catch block
		}
	}
	
	public static int getMaxIdFrage(){
		String idstring = null;

		try {
			// defaultHttpClient
			DefaultHttpClient httpClient = new DefaultHttpClient();
			HttpGet httpGet = new HttpGet("http://10.0.2.2:8080/QuizCommunity/rest/webservice/frage/max");
			HttpResponse httpResponse = httpClient.execute(httpGet);
			HttpEntity httpEntity = httpResponse.getEntity();
			idstring = EntityUtils.toString(httpEntity);

		} catch (UnsupportedEncodingException e) {
			idstring = e.getMessage();
		} catch (ClientProtocolException e) {
			idstring = e.getMessage();
		} catch (IOException e) {
			idstring = e.getMessage();
		}
		// return XML
		return Integer.parseInt(idstring);
	}

}
